import { _decorator, Component, Node, UITransform } from 'cc';
import { eventsOnEnable, preloadEvent } from '../../core_cc/EventUtil';
import EventName from './EventName';
const { ccclass, property } = _decorator;

@eventsOnEnable()
@ccclass('Player')
export class Player extends Component {

    container: Node = null;

    yMax: number = 0;
    yMin: number = 0;
    xMax: number = 0;
    xMin: number = 0;

    jumpSpeed: number = 0;
    moveX: number = 0;

    readonly moveMaxSpeed: number = 300;
    readonly jumpMaxSpeed: number = 500;
    readonly downSpeed: number = 1000;

    protected onLoad(): void {
        this.container = this.node.parent;

        const { width, height } = this.container.uiTransform;

        this.yMax = height / 2 - this.node.h / 2;
        this.yMin = -height / 2 + this.node.h / 2;

        this.xMax = width / 2 - this.node.w / 2;
        this.xMin = -width / 2 + this.node.w / 2;

        console.log(
            this.yMax,
            this.yMin,
            this.xMax,
            this.xMin
        )

    }

    @preloadEvent(EventName.left)
    @preloadEvent(EventName.right)
    onEventLeftOrRight(event: string) {
        if (event == EventName.left) {
            console.log("left");
            this.moveX = -this.moveMaxSpeed;
        } else {
            console.log("right");
            this.moveX = this.moveMaxSpeed;
        }
        this.jumpSpeed = this.jumpMaxSpeed;
    }


    update(dt: number) {
        // if (inRange(this.xMin, this.xMax, this.node.x)) {
        //     this.node.x += this.moveX * dt;
        // } else {
        //     this.moveX = 0;
        //     this.node.x = this.node.x > 0 ? this.xMax : this.xMin;
        // }

        // if (inRange(this.yMin, this.yMax, this.node.y)) {
        //     let moveY = this.jumpSpeed;
        //     if (this.jumpSpeed > -this.jumpMaxSpeed)
        //         this.jumpSpeed -= this.downSpeed * dt;
        //     let y = this.node.y + moveY * dt;
        //     this.node.y = matchx.clamp(this.yMin, this.yMax, y);
        // } else {
        //     if (this.node.y > 0 && this.node.y != this.yMax) {
        //         this.node.y = this.yMax;
        //         this.jumpSpeed = 0;
        //     } else {
        //         this.node.y = this.yMin;
        //         this.jumpSpeed = this.jumpMaxSpeed;
        //     }
        // }

        //大道至简
        let x = this.node.x + this.moveX * dt;
        this.node.x = matchx.clamp(this.xMin, this.xMax, x);

        if (this.yMin == this.node.y) this.jumpSpeed = this.jumpMaxSpeed;
        let moveY = this.jumpSpeed;
        if (this.jumpSpeed > -this.jumpMaxSpeed)
            this.jumpSpeed -= this.downSpeed * dt;
        let y = this.node.y + moveY * dt;
        this.node.y = matchx.clamp(this.yMin, this.yMax, y);
    }



}


